home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: howland.reston.ans.net!psinntp!psinntp!psinntp!psinntp!atluw04!not-for-mail
- From: Guru Chandar <GCHAN@dbsoftware.com>
- Subject: Assignment op. for an object with reference member
- Message-ID: <3163FE18.28D@dbsoftware.com>
- Date: Thu, 04 Apr 1996 11:51:36 -0500
- Organization: Dun & Bradstreet Software
- X-Mailer: Mozilla 2.0GoldB1 (WinNT; I)
- MIME-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
-
- I ran into a situation where I was asked to write an assignment operator
- for a class that has a reference to another class as a data member.
- The requirement was that after the assignment, the reference on the target object
- must refer to the same object that the reference on the source does.
-
- I have given an example below.
-
- #include <iostream.h>
-
- class A
- {
- public:
- A(int x) :x_(x){}
- friend ostream& operator<<(ostream& os,const A& a)
- {os << "x_ = " << a.x_; return os;}
- private:
- int x_;
- };
-
- class B
- {
- public:
- B(A& a) : a_(a) {}
- B(B& src): a_(src.a_){}
- B& operator=(B& src);
-
- friend ostream& operator<<(ostream& os,const B& b)
- {os << b.a_ << endl; return os;}
- private:
- A& a_;
- };
-
- B&
- B::operator=(B& src)
- {
- if (this == &src)
- return *this;
-
- // a_ = src.a_ won't work, it will change the value of what a_ refers to!
-
- //Invoke the copy constructor on this object
- this->B::B(src); // if you take out this-> the behavior changes on VC++ 4.0
-
- return *this;
- }
-
- void main()
- {
- A a1(1);
- A a2(2);
-
- B b1(a1);
- B b2(a2);
-
- cout << "b1 = " << b1;
- cout << "b2 = " << b2;
-
- b1 = b2; // after this b1.a_ should refer to b2.a_ i.e a2
-
- cout << "b1 = " << b1;
- cout << "b2 = " << b2;
- }
-
- When I run this on VC++ 4.0
- The output is :
- b1 = x_ = 1
- b2 = x_ = 2
- b1 = x_ = 2
- b2 = x_ = 2
-
- But on HP C++ I get a compilation error.
-
- I have two questions:
-
- 1. Is it legel to even attempt to change a reference after it is initialized?
- ARM & other books say that the only way to assign a value to a reference
- is when you initialize it.
-
- 2. If the answer to Q1 is Yes, then is the code given above, especially the
- syntax to invoke the copy constructor explicitly on an object:
-
- this->B::B(src); // if you take out this-> the behavior changes on VC++ 4.0
-
- valid? Is it supported in the standard?
-
- Any advice, thoughts on this will be appreciated.
-
- --------------------------------------------------------------------------------
-
-